<template>
  <div class="upload-box">
    <van-uploader
      accept="video/*"
      upload-icon="imgs/upload.png"
      :upload-text="uploadText"
      :before-read="startUpload"
    >
      <van-image v-if="snapshot" fit="contain" :src="snapshot"></van-image>
    </van-uploader>
    <div class="tip">
      <div>
        <p>视频文件将被转码为算法可接受的格式</p>
      </div>
      <div>
        <p v-if="uploadProgress >= 1">点击进行切换</p>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import moment from 'moment'
import { apiAxios } from '@/api/axios'
import OSS from 'ali-oss'

@Component
export default class VideoInput extends Vue {
  uploadProgress = 0
  transcoding = false
  transcodeError = false
  snapshot = ''
  uploading = false
  uploadError = false

  get uploadText () {
    if (this.uploading) {
      return `上传进度： ${Math.round(this.uploadProgress * 100)} %`
    } else {
      if (this.uploadProgress === 0) {
        return '上传视频'
      } else if (this.uploadProgress >= 1) {
        if (this.transcoding) {
          return '上传完成，转码中'
        } else if (this.transcodeError) {
          return '转码失败，请替换文件后重试'
        } else {
          return '上传完成'
        }
      }
    }
    return '上传视频'
  }

  async startUpload (file: File) {
    this.uploading = true
    this.uploadProgress = 0
    this.uploadError = false
    this.snapshot = ''
    this.transcoding = true
    this.transcodeError = false
    this.$emit('dataOk', false)
    this.$store.state.api.videos = []
    const objectId = moment().format('YYYY-MM-DD/x')
    const res = await apiAxios.post('/oss/uploadParam/' + moment().format('x'), {})

    const clt = new OSS({
      region: res.data.region,
      accessKeyId: res.data.accessKeyId,
      accessKeySecret: res.data.accessKeySecret,
      stsToken: res.data.stsToken,
      bucket: res.data.bucket
    })
    const options = {
      progress: this.progress,
      partSize: 100 * 1024
    }
    try {
      await clt.multipartUpload(objectId, file, options)
      this.uploading = false
      const res = (await apiAxios.get('/oss/urlInfo/' + objectId)) as any
      this.transcoding = false
      if (res.code === 0) {
        this.snapshot = res.data.snapshot
        this.$store.state.api.videos = [res.data.url]
        this.$emit('dataOk', true)
      } else {
        this.transcodeError = true
      }
    } catch (err) {
      console.log(err)
      this.uploadError = true
      this.uploading = false
      this.uploadProgress = 0
    }
  }

  progress (p : number, checkpoint: any) {
    this.uploadProgress = p
  }
}
</script>

<style scoped lang="less">
@import './common';
</style>
